import React, { FC, useEffect, useRef, useState } from 'react'
import { Form, Input, Modal, Radio, DatePicker, message, Image, Space, Button, Popconfirm, Row, Col } from 'antd'
import Draggable, { DraggableData, DraggableEvent } from 'react-draggable'
import AppUpload from '@/components/AppUpload'
import { useSetState } from 'ahooks'
import { Method } from 'axios'
import dayjs from 'dayjs'

interface Iprops {
  isOpenEdit: boolean
  setIsOpenEdit: any
  data?: any
  onOkAction?: any
}

interface IState {
  head_thumb: string
  year: any
}

const fetchUsers = (p: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const data = { name: 'jikey', ...p }
      resolve(data)
    }, 200)
  })
}

const dateFormat = 'YYYY-MM-DD'

const EditUser: FC<Iprops> = ({ data, isOpenEdit, setIsOpenEdit, onOkAction }) => {
  const [state, setState] = useSetState<IState>({ head_thumb: '', year: '' })
  const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 })
  const draggleRef = useRef<HTMLDivElement>(null)
  const [disabled, setDisabled] = useState(false)
  const [form] = Form.useForm()
  const isEdit = !!data
  const title = !isEdit ? '添加用户' : '修改用户'
  const { validateFields } = form

  // 日期配置
  const dateConfig = {
    rules: [{ required: true, message: '请选择日期' }],
  }

  // 上传配置
  const uploadConfig = {
    maxCount: 1,
    accept: '.jpg,.jpeg,.png',
    action: `${process.env.REACT_APP_API_URL}/upload`,
  }

  // init
  useEffect(() => {
    if (!data) {
      form.resetFields()
      return
    }

    if (isEdit) {
      data.year = '2022'
      form.setFieldsValue({ year: dayjs(data?.year, dateFormat) })
      setState({ year: data.year, head_thumb: data.head_thumb })
      delete data.year // 解决data.clone报错问题
      form.setFieldsValue(data)
    }
  }, [data])

  // 调用接口
  const handleFinish = (params: any) => {
    let method: Method = 'post'
    let txt = '添加成功'
    let id = ''

    if (isEdit) {
      method = 'put'
      txt = '修改成功'
      id = data.uuid
    }

    const fParams = { id, type: method, params }
    fetchUsers(fParams).then(() => {
      message.success(txt)

      setTimeout(() => {
        setIsOpenEdit(false)
        onOkAction && onOkAction()
        form.resetFields()
      }, 500)
    })
  }

  // 处理完成
  const onFinish = async () => {
    validateFields().then((values: any) => {
      handleFinish(values)
    }).catch((err) => {
      console.log('Failed:', err)
    })
  }

  const onYearChange = (date: any, dateString: string) => {
    setState({ year: dateString })
  }

  // 取消
  const handleCancel = () => {
    setIsOpenEdit(false)
  }

  // 关闭后
  const afterClose = () => {
    form.resetFields()
    setState({ head_thumb: '', year: '' })
  }

  // 上传成功
  const onUploadSuccess = ({ url }: { url: string }) => {
    setState({ head_thumb: url })
  }

  // 上传失败
  const onUploadFail = () => { }

  const onDelImg = (url: string) => {
    fetchUsers({ params: { url }, type: 'get' }).then(() => {
      message.success('删除成功')
      setState({ head_thumb: '' })
    }).catch(() => {
      setState({ head_thumb: '' })
    })
  }

  const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window.document.documentElement
    const targetRect = draggleRef.current?.getBoundingClientRect()
    if (!targetRect) {
      return
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    })
  }

  const getTitle = (
    <div
      style={{ width: '100%', cursor: 'move' }}
      onMouseOver={() => {
        if (disabled) {
          setDisabled(false)
        }
      }}
      onMouseOut={() => {
        setDisabled(true)
      }}
      onFocus={() => { }}
      onBlur={() => { }}
    > {title}
    </div>
  )

  return (
    <Modal
      getContainer={false}
      title={getTitle}
      forceRender
      open={isOpenEdit}
      onOk={onFinish}
      destroyOnClose
      onCancel={handleCancel}
      afterClose={afterClose}
      modalRender={(modal) => (
        <Draggable disabled={disabled} bounds={bounds} onStart={(event, uiData) => onStart(event, uiData)}>
          <div ref={draggleRef}>{modal}</div>
        </Draggable>
      )}
    >
      <Form
        className="app-vertical-form"
        name="basic"
        layout="vertical"
        form={form}
        preserve={false}
        onFinish={onFinish}
        autoComplete="off"
        initialValues={{
          sex: 1,
        }}
      >
        <Form.Item
          label="姓名"
          name="email"
          rules={[{ required: true, message: '请输入姓名' }, { whitespace: true, message: '姓名不能为空' }]}
        >
          <Input placeholder="请填写姓名" />
        </Form.Item>
        <Form.Item
          label="身份证号"
          name="gender"
          rules={[{ required: true, message: '请填写身份证号' }]}
        >
          <Input placeholder="请填写身份证号" />
        </Form.Item>
        <Row>
          <Col span={12}>
            <Form.Item
              label="生日"
              name="year"
              wrapperCol={{ span: 22 }}
              {...dateConfig}
            >
              <DatePicker style={{ width: '100%' }} onChange={onYearChange} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="性别"
              name="sex"
              rules={[{ required: true, message: '请选择性别' }]}
              wrapperCol={{ span: 24 }}
            >
              <Radio.Group value={1}>
                <Radio value={1}>男</Radio>
                <Radio value={2}>女</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
        </Row>
        <Form.Item
          label="照片"
          name="head_thumb"
          rules={[{ message: '请学生照片' }]}
          wrapperCol={{ span: 12 }}
        >
          {state.head_thumb && (
            <Space direction="vertical" className="thumb-space">
              <Image width={60} src={process.env.REACT_APP_HOST + state?.head_thumb} />
              <Popconfirm title="确定要删除吗?" onConfirm={() => onDelImg(state?.head_thumb)}>
                <Button type="default" danger size="small">删除</Button>
              </Popconfirm>
            </Space>
          )}
          {!state.head_thumb && <AppUpload title="上传照片" config={uploadConfig} onSuccess={onUploadSuccess} onFail={onUploadFail} />}
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default EditUser
